from nicegui import ui
import plotly.graph_objects as go


class PointVisualizer:
    def __init__(self):
        self.points = []

        # 创建输入框
        with ui.row().classes('items-center'):
            self.x = ui.number(label='X坐标').props('outlined')
            self.y = ui.number(label='Y坐标').props('outlined')
            self.z = ui.number(label='Z坐标').props('outlined')

        # 操作按钮
        with ui.row():
            ui.button('添加点', on_click=self.add_point).props('icon=add color=positive')
            ui.button('删除最后点', on_click=self.remove_last_point).props('icon=remove color=negative')

        # 创建3D图表
        self.fig = go.Figure()
        self.plot = ui.plotly(self.fig).classes('w-full h-128')
        self.update_plot()

    def get_input_values(self):
        """获取并验证输入值"""
        try:
            return (
                float(self.x.value),
                float(self.y.value),
                float(self.z.value)
            )
        except ValueError:
            return None

    def add_point(self):
        """添加点"""
        coords = self.get_input_values()
        if coords:
            self.points.append(coords)
            self.update_plot()

    def remove_last_point(self):
        """删除最后一个点"""
        if self.points:
            self.points.pop()
            self.update_plot()

    def update_plot(self):
        """更新3D图表"""
        self.fig.data = []  # 清空现有数据

        if self.points:
            xs, ys, zs = zip(*self.points)

            # 创建新的散点图
            scatter = go.Scatter3d(
                x=xs,
                y=ys,
                z=zs,
                mode='markers',
                marker=dict(
                    size=6,
                    color='#FF5252',
                    opacity=0.8
                )
            )

            # 更新图表布局
            self.fig.add_trace(scatter)
            self.fig.update_layout(
                scene=dict(
                    xaxis_title='X',
                    yaxis_title='Y',
                    zaxis_title='Z',
                    aspectmode='data'
                ),
                margin=dict(l=0, r=0, b=0, t=0),
                showlegend=False
            )

        # 强制更新图表
        self.plot.update()


if __name__ in {"__main__", "__mp_main__"}:
    PointVisualizer()
    ui.run(
        title="3D点可视化工具",
        port=8080,
        dark=True,
        reload=False
    )